package com.xrun.risk.service.process.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xrun.cmap.WfMapUtils;
import com.xrun.common.constant.ThirdTypeConstants;
import com.xrun.ocenengine.dto.vo.AgentTokenAndTypeVo;
import com.xrun.risk.domain.WfRiskDeleteTask;
import com.xrun.risk.domain.WfRiskDeleteTaskAdter;
import com.xrun.risk.domain.WfRiskDeleteTaskAdterContentDetail;
import com.xrun.risk.mapper.WfRiskDeleteTaskAdterContentDetailMapper;
import com.xrun.risk.service.process.Process;
import com.xrun.risk.util.AdMaterialUtilV2;
import com.xrun.risk.util.QianchuanMaterialUtilV2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ImageProcessImpl implements Process {
    @Autowired
    private QianchuanMaterialUtilV2 qianchuanMaterialUtilV2;
    @Autowired
    private WfRiskDeleteTaskAdterContentDetailMapper wfRiskDeleteTaskAdterContentDetailMapper ;
    @Autowired
    private AdMaterialUtilV2 adMaterialUtilV2 ;
    @Override
    public Object execute(WfRiskDeleteTask wfRiskDeleteTask,
                        WfRiskDeleteTaskAdter record,
                          AgentTokenAndTypeVo vo) {

        //获取所有素材id
        List<String> imageIdsAd = this.getImageIds(WfMapUtils.get(vo.getTokenTableId()),
                record.getAdvertiserId() + "",vo.getThirdType());
        if (CollectionUtil.isEmpty(imageIdsAd)){
            return null ;
        }
         //构造对象
        Map<String, WfRiskDeleteTaskAdterContentDetail> contentDetails = WfRiskDeleteTaskAdterContentDetail.getListEntityContent(imageIdsAd, record, vo, wfRiskDeleteTask, "IMAGE");

        //巨量删除
       List<WfRiskDeleteTaskAdterContentDetail> results = this.imageDel(vo.getTokenTableId(), record.getAdvertiserId()+ "",
               imageIdsAd,contentDetails,vo.getThirdType());

        //本地存储
        wfRiskDeleteTaskAdterContentDetailMapper.batchInsert(results);

      return null ;
    }






    /**
     * 获取所有图片id
     * @param accessToken
     * @param accountId
     * @param thirdType
     * @return
     */
    public List<String> getImageIds(String accessToken, String accountId,String thirdType) {
        List<String> objects = new ArrayList<>();
        int currentPage = 1;
        int totalPage = 1;

        do {
             JSONObject jsonObject =null ;
             if(ThirdTypeConstants.QIANCHAN.equals(thirdType)) {
                 jsonObject = qianchuanMaterialUtilV2.listAdMaterialImageByAccountId(
                         accessToken, accountId, currentPage, 100, null,
                         null, null, null);
             }else {
                 jsonObject = adMaterialUtilV2.listAdMaterialImageByAccountId(
                         accessToken, accountId, currentPage, 100, null,
                         null, null, null);
             }

            totalPage = jsonObject.getJSONObject("data").getJSONObject("page_info").getIntValue("total_page");
            currentPage++;
            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
            if (CollectionUtil.isNotEmpty(jsonArray)) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    objects.add(jsonArray.getJSONObject(i).getString("id"));
                }
            }
        } while (currentPage <= totalPage);

        return objects;
    }


    /**
     * qc 删除数据
     *
     * @param tokenTableId
     * @param accountId
     * @param imageIdsQC
     * @param thirdType
     * @return
     */
    private List<WfRiskDeleteTaskAdterContentDetail> imageDel(String tokenTableId, String accountId, List<String> imageIdsQC, Map<String, WfRiskDeleteTaskAdterContentDetail> imageMap, String thirdType) {
        List<List<String>> split = ListUtil.split(imageIdsQC, 100);
            for (List<String> splitImageIds : split) {
             JSONObject jsonObject = null ;
             JSONArray jsonArray = null ;
             if (ThirdTypeConstants.AD.equals(thirdType)){
                     jsonObject =   adMaterialUtilV2.delImage(accountId,WfMapUtils.get(tokenTableId), splitImageIds);
             }else {
                     jsonObject =   qianchuanMaterialUtilV2.delImage(accountId,WfMapUtils.get(tokenTableId), splitImageIds);
             }
            jsonArray = jsonObject.getJSONObject("data").getJSONArray("fail_image_ids");

             if (CollectionUtil.isNotEmpty(jsonArray)){
                    for (int i = 0; i < jsonArray.size(); i++) {
                        String imageId = jsonArray.getString(i);
                        //有问题的移掉
                       splitImageIds.remove(imageId);
                        WfRiskDeleteTaskAdterContentDetail one = imageMap.get(imageId);
                        if (one!=null){
                              one.setClearStatus("2");//2清理失败
                              one.setFailReason(jsonObject.getString("message"));
                              imageMap.put(imageId,one);
                        }
                    }
                }
             //如果移除掉所有有问题的，还有剩下的，说明这部分就是成功的
             if (CollectionUtil.isNotEmpty(splitImageIds)){
                 for (String imageId : splitImageIds) {
                     WfRiskDeleteTaskAdterContentDetail one = imageMap.get(imageId);
                     one.setClearStatus("1");//1清理成功
                     imageMap.put(imageId,one);
                 }
             }
         }
        return new ArrayList<>(imageMap.values());
    }
}
